"""
让聊天带有记忆
1.创建带历史消息得占位符的提示词模板 ChatPromptTemplate.from_messages
2.创建普通的链
3.创建带有记忆可运行的链
from langchain_core.runnables import RunnableWithMessageHistory
RunnableWithMessageHistory(
    普通链，
    取session_history方法(自定义)，
    提示词模板问题变量名,
    提示词模板占位符变量名)
4.记忆可运行的链invoke调用，
invoke参数 为json即字典 如 {"question":"xxx"},config={"configurable":{"session_id":1}}

重要类
1.聊天消息历史类  from langchain_community.chat_message_histories import ChatMessageHistory
2.带记忆消息可运行类  from langchain_core.runnables import RunnableWithMessageHistory

"""
from model_utils import getLLM
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.output_parsers import StrOutputParser
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables import RunnableWithMessageHistory

llm = getLLM()

template = ChatPromptTemplate.from_messages([
    ("system","请用中文回答"),
    MessagesPlaceholder(variable_name="history"),
    ("human","{question}")
])

parser = StrOutputParser()

chain = template | llm | parser

store = {}

def get_by_session_id(session_id):
    if session_id not in store:
        store[session_id] = ChatMessageHistory()
    return store[session_id]

run_with_chain = RunnableWithMessageHistory(chain,
                                            get_by_session_id,
                                            input_messages_key="question",
                                            history_messages_key="history")

config = {"configurable":{"session_id":"id12345"}}

r = run_with_chain.invoke({"question":"我叫张三"},config=config)
print(r)
print(store)
print("----------------")
r = run_with_chain.invoke({"question":"我叫什么名字"},config=config)
print(r)